/**
 *
 */
package cn.hg.jbsa.admin.handler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.jfinal.handler.Handler;
import com.jfinal.kit.HandlerKit;
import com.jfinal.kit.StrKit;

import cn.hutool.core.util.ArrayUtil;

/**
 * 伪静态处理Handler
 *
 * @author Golly
 */
public class FakeStaticHandler extends Handler {

    private String[] excludeViewPostfixs = new String[] {};
    private String viewPostfix;

    public FakeStaticHandler () {
        this.viewPostfix = ".html";
    }

    /**
     * @param viewPostfix
     * @param excludeViewPostfixs
     */
    public FakeStaticHandler (String viewPostfix, String... excludeViewPostfixs) {

        if (StrKit.isBlank(viewPostfix)) {
            throw new IllegalArgumentException("viewPostfix can not be blank.");
        }

        this.viewPostfix = viewPostfix;
        this.excludeViewPostfixs = excludeViewPostfixs;
    }

    /*
     * (non-Javadoc)
     * @see com.jfinal.handler.Handler#handle(java.lang.String,
     * javax.servlet.http.HttpServletRequest,
     * javax.servlet.http.HttpServletResponse, boolean[])
     */
    @Override
    public void handle (String target, HttpServletRequest request, HttpServletResponse response, boolean[] isHandled) {

        if ("/".equals(target)) {
            this.next.handle(target, request, response, isHandled);
            return;
        }

        if (!ArrayUtil.contains(this.excludeViewPostfixs, target)) { // 如果URL前缀不在排除前缀列表范围内，则启用伪静态

            if (target.indexOf('.') == -1) {
                HandlerKit.renderError404(request, response, isHandled);
                return;
            }

            int index = target.lastIndexOf(this.viewPostfix);

            if (index != -1) {
                target = target.substring(0, index);
            }

        }

        this.next.handle(target, request, response, isHandled);
    }

}
